package com.stox.client.ui.javafx.chartingy.model.node;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.paint.Color;
import javafx.scene.shape.ClosePath;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;

import com.stox.client.ui.javafx.chartingy.model.plot.Data;
import com.stox.client.ui.javafx.chartingy.model.plot.Plot;
import com.stox.client.ui.javafx.core.util.CSS;
import com.stox.client.ui.javafx.core.util.UI;

public class AreaPlotNode<T, V> extends PlotNode<T, V> {

	private final Path path = new Path();
	private final Plot<T, V> plot;

	public AreaPlotNode(final Plot<T, V> plot) {
		this.plot = plot;
		getChildren().add(path);
		UI.style(path, CSS.plotNode, CSS.areaPlotNode);
		plot.colorProperty().addListener(new ChangeListener<Color>() {
			@Override
			public void changed(final ObservableValue<? extends Color> observable, final Color oldValue, final Color newValue) {
				updateColor();
			}
		});
		updateColor();
	}

	public void updateColor() {
		final String color = UI.web(plot.getColor());
		path.setStyle("-fx-plot-node-color:" + color + "");
	}

	@Override
	public void preLayout() {
		path.getElements().clear();
	}


	private double firstX;
	private double firstY;
	private double lastX;

	@Override
	public void layout(final Data<T, V> data, final double x, final double unitWidth) {
		final double y = getDisplayPosition(data.getValue());
		if (path.getElements().isEmpty()) {
			firstX = x - (unitWidth / 2);
			firstY = y;
			path.getElements().add(new MoveTo(firstX, firstY));
		} else {
			lastX = x + unitWidth;
			path.getElements().add(new LineTo(lastX, y));
		}
	}

	@Override
	public void postLayout() {
		final double y = plot.getChart().getChartContentArea().getHeight();
		path.getElements().add(new LineTo(lastX, y));
		path.getElements().add(new LineTo(firstX, y));
		path.getElements().add(new LineTo(firstX, firstY));
		path.getElements().add(new ClosePath());
	}

	@Override
	public Plot<T, V> getPlot() {
		return plot;
	}

}
